//
//  FFLocationManager.m
//  Common
//
//  Created by IT.Bear on 16/5/18.
//  Copyright © 2016年 IT.Bear. All rights reserved.
//

#import "FFLocationManager.h"
#import "FFCache.h"
#import "ZipArchive.h"
#import "FFRegion.h"
#import "FFMacro.h"

#define TICK_START   NSDate *tickTime = [NSDate date];
#define TICK_END   NSLog(@"Time: %f", -[tickTime timeIntervalSinceNow]);

static FFLocationManager *location;
@interface FFLocationManager ()
@property (nonatomic,copy)FFLaunchTaskFinished finished;
@property (nonatomic ,strong) NSMutableDictionary *addressListDic;
@end

@implementation FFLocationManager

+ (FFLocationManager *)sharedInstance {
    static dispatch_once_t oncetoken;
    dispatch_once(&oncetoken,^{
        if (!location) {
            location = [[self alloc] init];
        }
    });
    return location;
}

-(NSArray *)regionList{
    
    if (!_regionList || [_regionList count]==0) {
        
        _regionList = [FFCache queryCache:KEYREGIONS];
    }
    return _regionList;
}

- (void)loadLocalRegion{
    
    TICK_START
    
    _addressListDic = [NSMutableDictionary dictionary];
    
    NSString * documentsPath = @"";
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    documentsPath = [documentsPath stringByAppendingPathComponent:[paths objectAtIndex:0]];
    
    ZipArchive* zip = [[ZipArchive alloc] init];
    
    NSString * zipFile = [[NSBundle mainBundle]pathForResource:@"AddressResource" ofType:@"zip"];
    NSString* unZipTo = documentsPath ;
    if( [zip UnzipOpenFile:zipFile] ){
        BOOL result = [zip UnzipFileTo:unZipTo overWrite:YES];
        if( NO==result ){
            //添加代码
//                        if (self.finished) {
//                            self.finished(NO);
//                        }
        }else{
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSData * data = [[NSData alloc]initWithContentsOfFile:[[zip unzippedFiles] objectAtIndex:0]];
                NSError * error;
                id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
                _addressListDic = (NSMutableDictionary *)jsonObject;
                [self dealWithDic:_addressListDic];
                NSFileManager *fileManager = [NSFileManager defaultManager];
                [fileManager removeItemAtPath:[[zip unzippedFiles] objectAtIndex:0] error:&error];

            });
        }
        [zip UnzipCloseFile];
    }
    TICK_END
    
}

- (void)dealWithDic:(NSDictionary *)dic
{
    NSMutableArray *regionList = [NSMutableArray array];
    NSDictionary *data = dic[@"data"];
    NSArray *data3 = data[@"children"];
    if (data3 && [data3 count]>0) {
        for (NSDictionary *regionDic in data3) {
            FFRegion *region = [[FFRegion alloc] initWithDictionary:regionDic];
            [regionList addObject:region];
        }
    }
    
    self.regionList = regionList;
    [FFCache initialize];
    [FFCache removeCacheForKey:KEYREGIONS];
    [FFCache addCache:KEYREGIONS obj:self.regionList type:FFCacheTypeRegions];
}

#pragma mark - BBGLaunchTask
- (void)launchTask:(FFLaunchTaskFinished)finished{
    //处理地址数据
    self.finished = finished;
    if (self.finished) {
        self.finished(YES);
    }
    [self loadLocalRegion];

}
- (void)handlerAddressList
{
    if (!self.regionList) {
        [self loadLocalRegion];
    }
}

- (NSString *)taskName{
    return @"地址库管理";
}

@end
